/**
 * 白名单
 */
function setResponse(req, res, next, origin='*') {
    res.header("Access-Control-Allow-Origin", origin);
    res.header("Access-Control-Allow-Headers", "Content-Type, X-Access-Token");
    res.header('Access-Control-Allow-Credentials', 'true');
    res.header("Access-Control-Allow-Methods","POST,GET,OPTIONS");
    if(req.method === 'OPTIONS') {
        res.sendStatus(200)
    }else{
        next();
    }
}

module.exports = (req, res, next) => {
    const releaseInterface = $config._dti.includes(req.path);

    if(releaseInterface) {
        setResponse(req, res, next);
    } else {
        const whiteList = process.env.WHITE_LIST.split(',');
        const origin = req.get("Origin");
        if (origin) {
            const allowOrigin = whiteList.find((url) => origin.indexOf(url) !== -1);
            if (allowOrigin) {
                setResponse(req, res, next, origin);
            }else{
                res.status(403).send({
                    code: 403,
                    msg: 'This domain doest not access rights.'
                });
            }
        }else{
            res.status(403).send({
                code: 403,
                msg: 'This domain doest not access rights.'
            });
        }
    }
}
